<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JSDoc: Source: flash/flashplayer.js</title>

    <script src="scripts/prettify/prettify.js"> </script>
    <script src="scripts/prettify/lang-css.js"> </script>
    <!--[if lt IE 9]>
      <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>

<body>

<div id="main">

    <h1 class="page-title">Source: flash/flashplayer.js</h1>

    



    
    <section>
        <article>
            <pre class="prettyprint source linenums"><code>/**
 * @module ChiVoxSDK/flash
 * @author Don Li &lt;kai.li@chivox.com>
 * @licence
 * Copyright (c) 2017 - 2020 ChiVox Inc. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

import Utils     from '../utils';
import cfg       from '../config.json';

import { tts }   from '../lib/public';
import swfobject from './swfobject';

const FLASH_PLAYER_URL        = `${cfg.host}/static/swf/AudioPlayer4JS_${cfg.flash_version}.swf`;
const EXPRESS_INSTALL_SWF_URL = `${cfg.host}/static/swf/expressInstall.swf`;

/* chivox flash player callbacks */
window._cfp_callbacks = {
    on_state_change: (code, message) => {
        var player = window.player;
        console.debug('current player event:', code, message);
        switch (code) {
            case '50414': //load starting
                if (player.__on_audio_load_start)
                    player.__on_audio_load_start(code, message);
                break;
            case '50400': //load successfully
                if (player.__on_audio_load_success)
                    player.__on_audio_load_success(code, message);
                break;
            case '50401': //play cmd starting
                if (player.__on_audio_play_start)
                    player.__on_audio_play_start(code, message);
                break;
            case '50402': //play cmd stop
                var _stop_callback = (message.stopType == '1') ? player.__on_audio_force_stop : player.__on_audio_play_stop;
                if (_stop_callback)
                    _stop_callback(code, message);
                break;
            default:
                console.warn('unregistered player event handler. ', code, message);
                break;
        }
    },

    on_flash_error: (code, message) => {
        console.error(code, message);
        window.player.options.onError(message);
    },

    on_flash_log: (message) => { console.debug(message); }
};

/**
 * Flash模式的音频播放器。&lt;br/>&lt;br/>
 * 基于Flash Player 10.0及以上版本插件设计开发，用于远程音频播放。
 */
export class FlashPlayer {
    /**
     * 创建一个Flash音频播放器。
     * @param {Object} options - 初始化参数。格式参见：{@link Default_ChiVoxPlayer_Options}
     */
    constructor(options) {
        this.options = options;
        this.player   = document.getElementById(this.options.playerid);
        if (!this.player) {
            this.player = document.createElement('div');
            this.player.id = this.options.playerid;
            document.body.appendChild(this.player);
        }

        this.can_play = false;
        this.loaded   = false;

        window.player = this;

        this.tts  = tts;
        this.__volume = 1;

        this.__on_audio_load_start   = null;
        this.__on_audio_load_success = null;
        this.__on_audio_load_failed  = null;

        this.__on_audio_play_start   = null;
        this.__on_audio_play_stop    = null;
        this.__on_audio_force_stop   = null;

        this.__embedswf();
    }

    __on_flash_loaded() {
        this.can_play = true;
        this.loaded   = true;
        this.player   = document.getElementById(this.options.playerid); //refresh

        if (this.options.onInit)
            this.options.onInit(0, null);
    }

    __embedswf() {
        let params  = { allowScriptAccess: 'always', wmode: this.options.wmode };
        let attribs = { id: this.options.playerid, name: this.options.playerid, wmode: this.options.wmode };
        let vars    = {
            flashLoadEventHandler: (code, message) => { window.g_flashplayer_is_load = true; },
            onPlayerEventHandler: "window._cfp_callbacks.on_state_change",
            errorEventHandler: "window._cfp_callbacks.on_flash_error"
        };

        if (cfg.debug)
            vars.jsLogCallback = "window._cfp_callbacks.on_flash_log";

        let _secs_passed = 0;
        let _interval    = 500;
        let _check_loading_status = () => {
            _secs_passed += _interval;

            if (window.g_flashplayer_is_load) {
                this.__on_flash_loaded();
                window.g_flashplayer_is_load = null;
            } else if (_secs_passed > cfg.load_flash_timeout) {
                this.options.onError(`timeout(${_secs_passed / 1000} secs) when loading swf: ${FLASH_PLAYER_URL}`);
                window.g_flashplayer_is_load = null;
            } else {
                setTimeout(_check_loading_status, _interval);
            }
        };

        window.g_flashplayer_is_load = false;
        swfobject.embedSWF(FLASH_PLAYER_URL, this.options.playerid, this.options.width, this.options.height, '10.0.0', EXPRESS_INSTALL_SWF_URL,
                vars, params, attribs);
        setTimeout(_check_loading_status, _interval);
    }

    /**
     * 远程加载音频。
     *
     * @param {Object} options - 加载音频所需的参数。参数有：
     * @param {string} options.url - 要加载的音频URL地址。
     * @param {callback} options.success - 加载音频成功的Callback，格式：() => {}。
     * @param {callback} options.error - 加载音频失败后的Callback，格式：(err) => {}。
     */
    load(options) {
        if (!this.loaded) { this.options.onError('not initialiazed'); return; }

        this.__on_audio_load_start   = options.start;
        this.__on_audio_load_success = options.success;
        this.__on_audio_load_failed  = options.error;

        let r = {};
        let params = {};

        try {

            r = this.player.loadAudioFromURL(options.url, params);
        } catch(e) {
            if (options.error)
                options.error(-1, e);
        }

        return r;
    }

    /**
     * 播放已经加载的音频。
     *
     * @param {Object} options - 播放音频所需的参数。参数有：
     * @param {int=} options.position - 播放位置，默认0。
     * @param {int=} options.duration - 播放时长。
     * @param {callback} options.onStart - 开始播放音频时的Callback，格式：(code, message) => {}。
     * @param {callback} options.onStop - 音频播放完成后的Callback，格式：(code, message) => {}。
     */
    play(options) {
        if (!this.loaded) { this.options.onError('not initialiazed'); return; }

        if (options.duration &lt;= 0) {
            this.options.onError('duration is 0'); return;
        }

        this.__on_audio_play_start = options.onStart;
        this.__on_audio_play_stop  = options.onStop;

        let r = {};
        try {
            r = this.player.startAudioPlay(0, options.duration, this.__volume * 100);
        } catch (e) {
            this.options.onError('play failed.', e);
        }

        return r;
    }

    /**
     * 手动停止音频播放。
     */
    stop(onStop, force = false) {
        if (!this.loaded) { this.options.onError('not initialiazed'); return; }

        this.__on_audio_force_stop = onStop;

        let r = {};
        try {
            r = this.player.stopAudioPlay();
        } catch (e) {
            this.options.onError('stop failed.', e);
        }

        return r;
    }

    /**
     * 重置播放器状态。
     */
    reset() {
        this.stop(null, true);

        this.__on_audio_load_start   = null;
        this.__on_audio_load_success = null;
        this.__on_audio_load_failed  = null;

        this.__on_audio_play_start   = null;
        this.__on_audio_play_stop    = null;
        this.__on_audio_force_stop   = null;
    }

    /**
     * 设置播放器播放音量。
     * @param {int} volume - 要设置的音量。 0 ~ 1
     */
    setVolume(volume) {
        if (!this.loaded) { this.options.onError('not initialiazed'); return; }

        if (typeof volume == 'number' &amp;&amp; isNaN(volume) == false) {
            if (volume &lt; 0) volume = 0;
            if (volume > 1) volume = 1;

            this.__volume = volume;

            try {
                this.player.adjustVolume(this.__volume * 100);
            } catch (e) {}
        }

        return this.__volume;
    }

    /**
     * 返回播放器播放音量。
     * @result {int} - 播放器当前音量。 0 ~ 1
     */
    getVolume() {
        if (!this.loaded) { this.options.onError('not initialiazed'); return; }
        return this.__volume;
    }

    getDuration() {}
    getPosition() {}
}

export default FlashPlayer
</code></pre>
        </article>
    </section>




</div>

<nav>
    <h2><a href="index.html">Home</a></h2><h3>Modules</h3><ul><li><a href="module-ChiVoxSDK.html">ChiVoxSDK</a></li><li><a href="module-ChiVoxSDK_flash.html">ChiVoxSDK/flash</a></li><li><a href="module-ChiVoxSDK_html5.html">ChiVoxSDK/html5</a></li><li><a href="module-ChiVoxSDK_lib.html">ChiVoxSDK/lib</a></li><li><a href="module-ChiVoxSDK_Paragraph.html">ChiVoxSDK/Paragraph</a></li><li><a href="module-ChiVoxSDK_score.html">ChiVoxSDK/score</a></li></ul><h3>Classes</h3><ul><li><a href="module-ChiVoxSDK_flash.FlashPlayer.html">FlashPlayer</a></li><li><a href="module-ChiVoxSDK_flash.FlashRecorder.html">FlashRecorder</a></li><li><a href="module-ChiVoxSDK_html5.Html5Player.html">Html5Player</a></li><li><a href="module-ChiVoxSDK_html5.Html5Recorder.html">Html5Recorder</a></li><li><a href="module-ChiVoxSDK_html5-VolumeBar.html">VolumeBar</a></li><li><a href="module-ChiVoxSDK_lib-EnScoreMap.html">EnScoreMap</a></li><li><a href="module-ChiVoxSDK_lib-StatusCode.html">StatusCode</a></li><li><a href="module-ChiVoxSDK_Paragraph-Paragraph.html">Paragraph</a></li><li><a href="module-ChiVoxSDK_score-Char.html">Char</a></li><li><a href="module-ChiVoxSDK_score-CnSentScore.html">CnSentScore</a></li><li><a href="module-ChiVoxSDK_score-CnWordScore.html">CnWordScore</a></li><li><a href="module-ChiVoxSDK_score-EnSentRec.html">EnSentRec</a></li><li><a href="module-ChiVoxSDK_score-EnSentScore.html">EnSentScore</a></li><li><a href="module-ChiVoxSDK_score-EnWordScore.html">EnWordScore</a></li><li><a href="module-ChiVoxSDK_score-Phone.html">Phone</a></li><li><a href="module-ChiVoxSDK_score-Word.html">Word</a></li><li><a href="module-ChiVoxSDK-ChiVoxSDK.html">ChiVoxSDK</a></li><li><a href="module-ChiVoxSDK-ControlPanel.html">ControlPanel</a></li><li><a href="module-ChiVoxSDK-Dialog.html">Dialog</a></li><li><a href="module-ChiVoxSDK-PlayerBuilder.html">PlayerBuilder</a></li><li><a href="module-ChiVoxSDK-ProgressBar.html">ProgressBar</a></li><li><a href="module-ChiVoxSDK-RecorderBuilder.html">RecorderBuilder</a></li></ul><h3>Namespaces</h3><ul><li><a href="public.html">public</a></li><li><a href="Utils.html">Utils</a></li></ul><h3>Global</h3><ul><li><a href="global.html#Default_ChiVoxPlayer_Options">Default_ChiVoxPlayer_Options</a></li><li><a href="global.html#Default_ChiVoxRecorder_Options">Default_ChiVoxRecorder_Options</a></li><li><a href="global.html#Default_ChiVoxSDK_Options">Default_ChiVoxSDK_Options</a></li><li><a href="global.html#Default_Paragraph_Options">Default_Paragraph_Options</a></li><li><a href="global.html#get_sig">get_sig</a></li><li><a href="global.html#tts">tts</a></li></ul>
</nav>

<br class="clear">

<footer>
    Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.5.5</a> on Thu Sep 21 2017 16:38:41 GMT+0800 (CST)
</footer>

<script> prettyPrint(); </script>
<script src="scripts/linenumber.js"> </script>
</body>
</html>
